package de.lgohlke.helper;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>HibernateUtil class.</p>
 *
 * @author lars
 * @version $Id: $
 */
public final class HibernateUtil
{
  private final static Logger log = LoggerFactory.getLogger(HibernateUtil.class);

  private HibernateUtil()
  {
    // ok
  }

  private static final Set<Class<?>> annotatedClasses = new HashSet<Class<?>>();
  private static SessionFactory      sessionFactory   = buildSessionFactory();

  /**
   * <p>Getter for the field <code>annotatedClasses</code>.</p>
   *
   * @return a {@link java.util.Set} object.
   */
  public static Set<Class<?>> getAnnotatedClasses()
  {
    return annotatedClasses;
  }

  /**
   * <p>reinit.</p>
   */
  public static void reinit()
  {
    sessionFactory = buildSessionFactory();
  }

  private static SessionFactory buildSessionFactory()
  {

    try
    {
      // Properties properties = new Properties();
      // String type = "mysql";
      // properties.put("hibernate.connection.driver_class", "com." + type + ".jdbc.Driver");
      // properties.put("hibernate.connection.url", "jdbc:mysql://localhost/WarrantMgmt");
      // properties.put("hibernate.connection.username", "root");
      // properties.put("hibernate.connection.password", "root");

      AnnotationConfiguration ac = new AnnotationConfiguration();
      // ac.addAnnotatedClass(Account.class);

      for (Class<?> c : annotatedClasses)
      {
        ac.addAnnotatedClass(c);
      }
      // ac.setProperties(properties);
      return ac.configure().buildSessionFactory();

    }

    catch (Throwable ex)
    {

      // Make sure you log the exception, as it might be swallowed

      log.error("Initial SessionFactory creation failed." + ex);

      throw new ExceptionInInitializerError(ex);

    }

  }

  /**
   * <p>Getter for the field <code>sessionFactory</code>.</p>
   *
   * @return a {@link org.hibernate.SessionFactory} object.
   */
  public static SessionFactory getSessionFactory()
  {

    return sessionFactory;

  }

}
